package com.personal.system.controller.act;

import cn.hutool.core.collection.ListUtil;
import com.personal.common.result.Result;
import com.personal.system.entity.ProcessDefinitionDTO;
import com.personal.system.entity.WorkflowExample;
import com.personal.system.service.act.WorkflowExampleService;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.model.payloads.GetProcessInstancesPayload;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.engine.RepositoryService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/act/processInstance")
public class ProcessInstanceController {

    @Resource
    private ProcessRuntime processRuntime;

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private WorkflowExampleService exampleService;

    @GetMapping(value = "/getInstances/{pageNum}/{pageSize}")
    public Result getInstances(@PathVariable int pageNum, @PathVariable int pageSize
            , ProcessDefinitionDTO dto) {
//        Page<ProcessInstance> processInstances = null;
        try {
//            processInstances = processRuntime.processInstances(Pageable.of(pageNum-1,  pageSize));
//            //System.out.println("流程实例数量： " + processInstances.getTotalItems());
//            List<ProcessInstance> list = processInstances.getContent();
//            //list.sort((y,x)->x.getProcessDefinitionVersion()-y.getProcessDefinitionVersion());
//            list.sort((y,x)->x.getStartDate().toString().compareTo(y.getStartDate().toString()));
//
//            List<HashMap<String, Object>> listMap = new ArrayList<HashMap<String, Object>>();
//            for(ProcessInstance pi:list){
//                HashMap<String, Object> hashMap = new HashMap<>();
//                hashMap.put("id", pi.getId());
//                hashMap.put("name", pi.getName());
//                hashMap.put("status", pi.getStatus());
//                hashMap.put("processDefinitionId", pi.getProcessDefinitionId());
//                hashMap.put("processDefinitionKey",       pi.getProcessDefinitionKey());
//                hashMap.put("startDate", pi.getStartDate());
//                hashMap.put("processDefinitionVersion", pi.getProcessDefinitionVersion());
//                //因为processRuntime.processDefinition("流程部署ID")查询的结果没有部署流程与部署ID，所以用repositoryService查询
//                ProcessDefinition pd = repositoryService.createProcessDefinitionQuery()
//                        .processDefinitionId(pi.getProcessDefinitionId())
//                        .singleResult();
//                hashMap.put("resourceName", pd.getResourceName());
//                hashMap.put("deploymentId", pd.getDeploymentId());
//                listMap.add(hashMap);
//            }
            WorkflowExample example = new WorkflowExample();
            example.setProcessDefinitionKey(dto.getKey());
            example.setName(dto.getName());
            List<WorkflowExample> workflowExamples = exampleService.selectWorkflowExampleList(example);
            List<WorkflowExample> page = ListUtil.page(pageNum - 1, pageSize, workflowExamples);

            Map<String, Object> map = new HashMap<>();
            map.put("listMap", page);
            map.put("total", workflowExamples.size());

            return Result.ok(map);
        } catch (Exception e) {
            return Result.fail("获取流程实例失败");
        }

    }


    //    //启动
//    @GetMapping(value = "/startProcess")
//    public AjaxResponse startProcess(@RequestParam("processDefinitionKey") String processDefinitionKey,
//                                     @RequestParam("instanceName") String instanceName,
//                                     @RequestParam("instanceVariable") String instanceVariable) {
//        try {
//
//            ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
//                    .start()
//                    .withProcessDefinitionKey(processDefinitionKey)
//                    .withName(instanceName)
//                    //.withVariable("content", instanceVariable)
//                    //.withVariable("参数2", "参数2的值")
//                    .withBusinessKey("自定义BusinessKey")
//                    .build());
//            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.SUCCESS.getCode(),
//                    GlobalConfig.ResponseCode.SUCCESS.getDesc(), processInstance.getName()+"；"+processInstance.getId());
//        } catch (Exception e) {
//            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.ERROR.getCode(),
//                    "创建流程实例失败", e.toString());
//        }
//    }
//
    //删除
    @GetMapping(value = "/deleteInstance")
    public Result deleteInstance(WorkflowExample example) {
        try {

            GetProcessInstancesPayload payload = new GetProcessInstancesPayload();
            payload.setBusinessKey(example.getId());
            Page<ProcessInstance> in = processRuntime.processInstances(Pageable.of(0, 1), payload);

            if (in.getTotalItems() > 0) {
                ProcessInstance processInstance = processRuntime.delete(ProcessPayloadBuilder
                        .delete()
                        .withProcessInstanceId(example.getInstanceId())
                        .build()
                );
            }

            int cou = exampleService.deleteWorkflowExampleById(example.getId());

            return Result.ok("删除成功：" + cou);
        } catch (Exception e) {
            return Result.fail("删除流程实例失败");
        }

    }

    //挂起冷冻
    @GetMapping(value = "/suspendInstance")
    public Result suspendInstance(WorkflowExample example) {
        try {
            ProcessInstance processInstance = processRuntime.suspend(ProcessPayloadBuilder
                    .suspend()
                    .withProcessInstanceId(example.getInstanceId())
                    .build()
            );

            WorkflowExample workflowExample = new WorkflowExample();
            workflowExample.setId(example.getId());
            workflowExample.setStatus("SUSPENDED");
            exampleService.updateWorkflowExample(workflowExample);

            return Result.ok(processInstance.getName());
        } catch (Exception e) {
            return Result.fail("挂起流程实例失败");
        }
    }

    //激活
    @GetMapping(value = "/resumeInstance")
    public Result resumeInstance(WorkflowExample example) {
        try {
            ProcessInstance processInstance = processRuntime.resume(ProcessPayloadBuilder
                    .resume()
                    .withProcessInstanceId(example.getInstanceId())
                    .build()
            );
            WorkflowExample workflowExample = new WorkflowExample();
            workflowExample.setId(example.getId());
            workflowExample.setStatus("RUNNING");
            exampleService.updateWorkflowExample(workflowExample);

            return Result.ok(processInstance.getName());
        } catch (Exception e) {
            return Result.fail("激活流程实例失败");
        }
    }
//
//
//    //获取参数
//    @GetMapping(value = "/variables")
//    public AjaxResponse variables(@RequestParam("instanceID") String instanceID) {
//        try {
//            if (GlobalConfig.Test) {
//                securityUtil.logInAs("wukong");
//            }
//            List<VariableInstance> variableInstance = processRuntime.variables(ProcessPayloadBuilder
//                    .variables()
//                    .withProcessInstanceId(instanceID)
//                    .build());
//
//            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.SUCCESS.getCode(),
//                    GlobalConfig.ResponseCode.SUCCESS.getDesc(), variableInstance);
//        }
//        catch(Exception e)
//        {
//            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.ERROR.getCode(),
//                    "获取流程参数失败", e.toString());
//        }
//    }


}
